package com.example.tingshu.controller;

import com.example.tingshu.model.ApiResult;
import com.example.tingshu.model.User;
import com.example.tingshu.service.AlbumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api")
public class ApiController {
    private final AlbumService albumService;

    @Autowired
    public ApiController(AlbumService albumService) {
        this.albumService = albumService;
    }

    @GetMapping("/album-list.json")
    public ApiResult albumList(
            @RequestParam(value = "keyword",required = false) String keyword
    ){
        ApiResult apiResult = new ApiResult();
        apiResult.success = true;

        try {
            apiResult.data = albumService.list(keyword);
        }catch (Exception exc){
            apiResult.success = false;
            apiResult.reason = exc.getMessage();
        }

        return apiResult;
    }

    @GetMapping("/my-album-list.json")
    public ApiResult myAlbumList(HttpSession session){
        ApiResult apiResult = new ApiResult();
        apiResult.success = true;

        try {
            User currentUser = (User) session.getAttribute("currentUser");
            if (currentUser == null){
                throw new RuntimeException("这个接口必须先登录");
            }

            apiResult.data = albumService.myList(currentUser.uid);
        }catch (Exception exc){
            apiResult.success = false;
            apiResult.reason = exc.getMessage();
        }

        return apiResult;
    }
}
